package com.demo.shiroDemo06.web;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;

import com.jfinal.core.ActionKey;
import com.jfinal.core.Controller;

public class LoginController extends Controller {

	//加一个/路径映射，避免访问项目根路径时jFinal框架报404异常
	@ActionKey("/")
	public void index() {
		redirect("/index.jsp");
	}
	
	@ActionKey("login")
	public void login() {
		HttpServletRequest req = getRequest();
		if ("GET".equalsIgnoreCase(req.getMethod())) {
			renderJsp("/login.jsp");
		}else {
			//登录失败，将异常信息通俗化
			String className = String.valueOf(req.getAttribute(FormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME));
			if (UnknownAccountException.class.getName().equals(className) || IncorrectCredentialsException.class.getName().endsWith(className)) {
				req.setAttribute(FormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME,"用户名/密码错误");
			}else if (AuthenticationException.class.getName().endsWith(className)) {
				req.setAttribute(FormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME,"其他错误");
			}
			renderJsp("/login.jsp");
		}
	}
}
